package com.archie.xunji.map.discover;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.archie.xunji.R;
import com.archie.xunji.map.Constans;
import com.archie.xunji.map.SetOnGetResult;
import com.archie.xunji.map.entity.DiscoverResultEntity;
import com.archie.xunji.map.tools.HttpAsyncTask;
import com.archie.xunji.map.tools.ParseJsonUtls;
import com.archie.xunji.map.tools.PlayerService;
import com.archie.xunji.map.view.CircleImageView;
import com.squareup.picasso.Picasso;

import java.util.HashMap;
import java.util.List;

public class DiscoverActivity extends Activity implements SetOnGetResult,
        AMap.InfoWindowAdapter, AMap.OnMapClickListener,
        AMap.OnMarkerClickListener, View.OnClickListener ,
        AMapLocationListener {

    private MapView mapView;
    private AMap aMap;

    private HttpAsyncTask updateMapTask;//更新地图任务
    private List<DiscoverResultEntity> datas;

    private ProgressDialog dialog;

    private int position;
    private boolean isPlay;
    private TextView time;
    private Intent playIntent;
    private ImageView player;
    private MyReceiver myReceiver;
    private LocationManagerProxy mLocationManagerProxy;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_discover);

        // 默认加载的地图
        mapView = (MapView) findViewById(R.id.map_discover_activity);
        mapView.onCreate(savedInstanceState);
        aMap = mapView.getMap();


        //自定义信息宽口
        aMap.setInfoWindowAdapter(this);
        aMap.setOnMarkerClickListener(this);
        aMap.setOnMapClickListener(this);
        initMapData();

        myReceiver = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter(Constans.BROADCAST_ACTION_UPDATETIME);
        registerReceiver(myReceiver, intentFilter);

    }

    private void initMapData() {
        // 网络请求，获取数据，更新地图
        String url = Constans.URL_DISCOVER;

        HashMap<String,String> params = new HashMap<String, String>();
        params.put("userinfoid", "-1");
        params.put("appuserid", "43502");
        params.put("t", "20151110163845");
        params.put("token","DA939220D9702734685BF6733E39DAC7C3F11C1B");
        params.put("sid", "mnScF1UJh4");
        params.put("imei", "4A061818D7F062836A3A279E0B99111B");
        params.put("os", "Android+4.2.2");
        params.put("key", "WANDOUJIA");
        params.put("type", "0");

        getData(url, params, "utf-8");
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();

        if (isPlay) {

            stopService(playIntent);
            unregisterReceiver(myReceiver);
        }
    }

    /**
     * 异步任务开启，获得数据
     * @param url
     * @param params
     * @param encode
     */
    private void getData(String url,HashMap<String,String> params,String encode) {

        // 显示进度条对话框
        initProgressDialog();
        dialog.show();

        updateMapTask = new HttpAsyncTask(params,encode,this);
        updateMapTask.execute(url);

    }

    private void initProgressDialog() {

        dialog = new ProgressDialog(this);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置进度条的形式为圆形转动的进度条
        dialog.setCancelable(true);// 设置是否可以通过点击Back键取消
        dialog.setCanceledOnTouchOutside(false);// 设置在点击Dialog外是否取消Dialog进度条
        dialog.setMessage("正在加载...");
    }

    /**
     * 点击顶部返回，退出当前Activity
     * @param view
     */
    public void btnBack(View view) {
        finish();
    }

    /**
     * 点击顶部中间框或搜索，进入搜索Activity
     * @param view
     */
    public void btnSearch(View view) {
        startActivity(new Intent(this, SearchActivity.class));
    }

    /**
     * 网络请求任务完成，回调的接口，在此进行地图的更新
     * @param result
     */
    @Override
    public void onGetResult(String result) {
        Log.d("debug", result);

        // 清楚数据和界面
        if(datas != null) {
            datas = null;

            List<Marker> mapScreenMarkers = aMap.getMapScreenMarkers();

            if(mapScreenMarkers != null){

                for (Marker mapScreenMarker : mapScreenMarkers) {
                    mapScreenMarker.remove();
                }

            }
        }

        datas = ParseJsonUtls.parseDiscoverResultEntity(result);

        updateMapSurface();
    }

    private void updateMapSurface() {

        if (datas != null) {


            for (int i = 0; i < datas.size(); i++) {
                DiscoverResultEntity entity = datas.get(i);

                //标记的属性设置
                MarkerOptions options = new MarkerOptions();
                options.visible(true);
                options.draggable(false);
                options.title(entity.getPlacename());
                options.position(new LatLng(entity.getLatitude(), entity.getLongitude()));

                //给地图添加标记
                Marker marker = aMap.addMarker(options);

                if(i==0) {
                    marker.showInfoWindow();

                    /**
                     * 定位地图的中心点和缩放级别
                     */
                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(entity.getLatitude(), entity.getLongitude())));
                    if(datas.size() == 1) {

                        aMap.moveCamera(CameraUpdateFactory.zoomTo(aMap.getMaxZoomLevel()));

                    }else{

                        aMap.moveCamera(CameraUpdateFactory.zoomTo(aMap.getMaxZoomLevel() - 7));

                    }
                }
            }

        }


        // 等待3s，进度对话框消失
        new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                dialog.dismiss();
            }
        }).start();


    }

    /**
     * 设置自定义的InfoWindow
     * @param marker
     * @return
     */
    @Override
    public View getInfoWindow(Marker marker) {
        View ret = getLayoutInflater().inflate(R.layout.activity_infowindow_map_discover,null);

        TextView placename = (TextView) ret.findViewById(R.id.placename_infowindow_map_discover_activity);
        player = (ImageView) ret.findViewById(R.id.player_infowindow_map_discover_activity);
        time = (TextView) ret.findViewById(R.id.time_infowindow_map_discover_activity);

        View bottom = ret.findViewById(R.id.bottom_infowindow_map_discover_activity);
        CircleImageView img = (CircleImageView) ret.findViewById(R.id.img_infowindow_map_discover_activity);
        TextView username = (TextView) ret.findViewById(R.id.username_infowindow_map_discover_activity);

        if(datas != null){

            for(int i=0;i<datas.size();i++){
                DiscoverResultEntity entity = datas.get(i);


                if(marker.getTitle().equals(entity.getPlacename())){

                    if(i!=position){
                        stopService(playIntent);
                        player.setImageResource(R.mipmap.ui_explore_lpayer);
                    }

                    position = i;
                    placename.setText(entity.getPlacename());

                    if(isPlay){
                        player.setImageResource(R.mipmap.ui_explore_pause);
                    }

                    Picasso.with(this).load(entity.getHeadurl())
                            .placeholder(R.mipmap.ui_def_user_ic)
                            .error(R.mipmap.ui_def_user_ic).into(img);
                    username.setText(entity.getUsername());

                    break;
                }

            }

            placename.setOnClickListener(this);
            player.setOnClickListener(this);
            bottom.setOnClickListener(this);

        }

        return ret;
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    @Override
    public void onMapClick(LatLng latLng) {
        List<Marker> mapScreenMarkers = aMap.getMapScreenMarkers();
        for (Marker mapScreenMarker : mapScreenMarkers) {
            mapScreenMarker.hideInfoWindow();
        }
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        marker.showInfoWindow();
        return false;
    }

    /**
     * 底部三个按钮的点击事件
     * @param view
     */
    public void onClickBottomButton(View view) {

        switch (view.getId()){
            case R.id.btnWatch:
                initMapData();
                break;

            case R.id.btnKind:
                startActivity(new Intent(this,SearchActivity.class));
                break;

            case R.id.btnAround:
                aroundMapDate();
                break;

        }

        //停止播放
        if(isPlay) {
            stopService(playIntent);
            isPlay = false;
        }

    }

    private void aroundMapDate() {

        // TODO 获取当前位置的经度和纬度
        getMyLocation();

        // 网络请求，获取数据，更新地图
        String url = Constans.URL_AROUND;

        HashMap<String,String> params = new HashMap<String, String>();
        params.put("userinfoid","-1");
        params.put("longitude","116.370446");
        params.put("latitude","40.03686");  //纬度
        params.put("appuserid", "43502");
        params.put("t","20151110164141");
        params.put("token","DA8ED1285D83350E7A7E6EDC1D4461BCE2B00EE6");
        params.put("sid", "mnScF1UJh4");
        params.put("imei","4A061818D7F062836A3A279E0B99111B");
        params.put("os", "Android+4.2.2");
        params.put("key", "WANDOUJIA");
        params.put("type", "1");

        getData(url, params, "utf-8");
    }

    private void getMyLocation() {

        mLocationManagerProxy = LocationManagerProxy.getInstance(this);
        //此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
        //注意设置合适的定位时间的间隔，并且在合适时间调用removeUpdates()方法来取消定位请求
        //在定位结束后，在合适的生命周期调用destroy()方法     
        //其中如果间隔时间为-1，则定位只定一次
        mLocationManagerProxy.requestLocationData(
                LocationProviderProxy.AMapNetwork, 60*1000, 15, this);
        mLocationManagerProxy.setGpsEnable(false);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){

            case R.id.placename_infowindow_map_discover_activity:
                Toast.makeText(this,"address",Toast.LENGTH_SHORT).show();
                break;

            case R.id.player_infowindow_map_discover_activity:
                isPlay = !isPlay;

                String url = datas.get(position).getAudiourl();
                playIntent = new Intent(this, PlayerService.class);
                playIntent.putExtra("url", url);

                startService(playIntent);

                if(isPlay){
                    player.setImageResource(R.mipmap.ui_explore_pause);
                }else{
                    player.setImageResource(R.mipmap.ui_explore_lpayer);
                }


                break;

            case R.id.bottom_infowindow_map_discover_activity:
                Toast.makeText(this,"item",Toast.LENGTH_SHORT).show();
                break;

        }
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if(aMapLocation != null && aMapLocation.getAMapException().getErrorCode() == 0){
            //获取位置信息
            Double geoLat = aMapLocation.getLatitude();
            Double geoLng = aMapLocation.getLongitude();

            Log.d("debug", "ddd--->" + geoLat + "," + geoLng);
            Toast.makeText(this,geoLat+","+geoLng,Toast.LENGTH_LONG).show();

        }
    }

    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }

    private class MyReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            //单位s
            long totalTime = intent.getLongExtra("totalTime",0);
            long currentTime = intent.getLongExtra("currentTime",0);

            long t = totalTime-currentTime;

            if(t>=0){

                String minute = t/60/10+""+t/60%10;
                String second = t%60/10+""+t%60%10;

                time.setText(minute+":"+second);

                if(t==0){
                    player.setImageResource(R.mipmap.ui_explore_lpayer);
                    isPlay = false;
                }
            }


        }
    }
}
